<template>
  <div ref="chartRef" class="chart" :style="{ width: width, height: height }"></div>
</template>

<script>
import * as echarts from 'echarts'
import ElementResizeDetector from 'element-resize-detector'
export default {
  name:'EChart',
  props: {
    option: {
      type: Object,
      required: true
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null,
      erd: null
    }
  },
  methods: {
    init() {
      this.chart = echarts.init(this.$refs['chartRef'])
      this.erd = ElementResizeDetector({ strategy: 'scroll', callOnAdd: true }) // 用于监听dom元素的尺寸变化
      // 当尺寸发生变化时，立即重绘图表，实现响应式效果
      this.erd.listenTo(this.$refs['chartRef'], () => {
        this.chart.resize()
      })
      this.chart.setOption(this.option)
    }
  },
  mounted() {
    this.init()
  },
  watch: {
    option: {
      handler(newVal) {
        this.chart.setOption(newVal)
      },
      deep: true
    },
    width: {
      handler() {
        this.chart.resize()
      }
    },
    height: {
      handler() {
        this.chart.resize()
      }
    }
  }
}
</script>
